package com.zhaoyue.study.concurrency.thread.threadgroup;

import java.util.Date;
import java.util.Random;
import java.util.concurrent.TimeUnit;

/**
 * Created with IntelliJ IDEA.
 * User: Administrator
 * Date: 2016/9/6
 * Time: 11:30
 * To change this template use File | Settings | File Templates.
 */
public class SearchTask implements Runnable {

    private Result result;
    public SearchTask(Result result){
        this.result = result;
    }

    public void run() {
        String name=Thread.currentThread().getName();
        System.out.printf("Thread %s: Start\n",name);
        try {
            doTask();
            result.setName(name);
        } catch (InterruptedException e) {
            System.out.printf("Thread %s: Interrupted\n",name);
            return;
        }
        System.out.printf("Thread %s: End\n",name);
    }

    private void doTask() throws InterruptedException {
        Random random=new Random((new Date()).getTime());
        int value=(int)(random.nextDouble()*100);
        System.out.printf("Thread %s: %d\n",Thread.currentThread(). getName(),value);
        TimeUnit.SECONDS.sleep(value);
    }

    public static void main(String[] args) {

        ThreadGroup threadGroup = new ThreadGroup("search");
        Result result = new Result();
        SearchTask searchTask = new SearchTask(result);

        for(int i=0;i<5;i++){
            Thread thread = new Thread(searchTask);
            thread.start();
            try{
                TimeUnit.SECONDS.sleep(1);
                System.out.println("Active count:");
                System.out.println(threadGroup.activeCount());
            }catch (Exception e){
                e.printStackTrace();
            }
        }

        System.out.println("List:");
        threadGroup.list();


    }
}
